package vip.websky.project.web.boot;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import vip.websky.project.common.config.SysConst;
import vip.websky.project.common.error.CommonsRuntimeException;
import vip.websky.project.common.error.ErrorCode;
import vip.websky.project.common.error.ErrorMessage;
import vip.websky.project.module.dto.RequestDTO;
import vip.websky.project.module.dto.ResponseDTO;
import vip.websky.project.web.config.InterfaceEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口控制层
 * 入口
 *
 * @createAt: 2017/8/10 14:07
 */
@Slf4j
@Controller
public class

Enter {

    @RequestMapping(value = "/common/interface", method = {RequestMethod.POST})
    public void enter( HttpServletRequest request,HttpServletResponse response,@RequestBody String  param){
        log.info("开始访问,参数:{}", param);
        long startTime = System.currentTimeMillis();
        RequestDTO requestDTO = JSONObject.parseObject(param,RequestDTO.class);
        log.info("访问接口:{},参数:{}", requestDTO.getInterCode(),requestDTO.getParam());

        ResponseDTO responseDTO = new ResponseDTO();
        try{
            InterfaceEnum interfaceEnum = InterfaceEnum.getInterfaceEnumByCode(requestDTO.getInterCode());
            if (interfaceEnum.isVerifyToken()){
                verifyToken(requestDTO.getTraceToken(),request.getRequestedSessionId());
            }
            responseDTO = interfaceEnum.getFunction().apply(requestDTO);
        }catch (CommonsRuntimeException e){
            log.error("错误信息信息:{}",e);
            responseDTO.setStatusCode(e.getCode());
            responseDTO.setStatusMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            log.error("异常信息:{}",e);
            responseDTO.setStatusCode(ErrorCode.UNEXPECTED_ERROR);
            responseDTO.setStatusMessage(ErrorMessage.UNEXPECTED_ERROR);
        }finally {
            long endTime = System.currentTimeMillis();
            log.info("访问接口:{},返回数据:{},总共用时:{}",requestDTO.getInterCode(),responseDTO,endTime-startTime);
            sendMessages(request,response,responseDTO);
        }

    }


    /**
     * 2、发送返回页面消息
     *
     * @param request  request
     * @param response response
     * @param json     发送的json内容
     */
    protected void sendMessages( HttpServletRequest request, HttpServletResponse response, Object json) {
        response.setCharacterEncoding(SysConst.SYS_CHARSET);
        response.setHeader("Content-Type", "charset=UTF-8");
        if (request != null && request.getHeader("sys-AGENT") != null
                && StrUtil.containsIgnoreCase(request.getHeader("sys-AGENT"), "Firefox")) {
            response.setContentType("application/json;charset=UTF-8");
        }
        try {
            log.info("返回页面结果消息：【{}】",json);
            String jsonResponse = JSON.toJSONString(json);
            response.getWriter().print(jsonResponse);
        } catch (Exception e) {
            log.info("sendMessages fail, Exception：{}", e);
        }
    }

    private void verifyToken(String token,String sessionId){
        String TOKEN = "";//产生 token; 保存token; 获取 token;
        if (!StringUtils.equalsIgnoreCase(token,TOKEN)){
            throw new CommonsRuntimeException(ErrorCode.TOKEN_VERIFY_ERROR,ErrorMessage.TOKEN_VERIFY_ERROR);
        }else{
            log.info("token verify ");
        }
    }
}
